<?php 

/**
 * 店铺员工管理
 * @Author      jiating
 * @DateTime    2018-04-12
 */

namespace app\admin\controller;

use app\admin\model\Recordconsumption;
use app\admin\model\Store as storeModel;
use app\admin\model\Producttype;
use app\admin\model\Product;
use app\admin\model\Storeproduct;
use app\common\model\Order;
use app\admin\model\Groupproduct;
use app\admin\model\Integralproducts;
use app\admin\model\Wxcomponentconf;
use app\common\model\Shoppingcar;

use app\common\BaseHelper;
use app\common\DictConstant;
use app\common\service\MiniProgramHelp;
use app\common\validate\IDMustBePostiveInt;
use distribution\DadaAddOrder;
use distribution\MerchantApi;
use gaodeapi\gaoDeApi;
use think\Db;
use think\Exception;
use \think\Request;

class Store extends Base{
	public $week = ['周一'=>'星期一','周二'=>'星期二','周三'=>'星期三','周四'=>'星期四','周五'=>'星期五','周六'=>'星期六','周日'=>'星期日'];

	public function __construct() {
		parent::__construct();
		$this->model = new storeModel();

	}
	
	public function index() {
        $Tenant = \app\common\model\Tenant::get(session('TENANT_ID'));
		$where = ['tenantId'=>session('TENANT_ID')];
		$list = $this->model->where($where)->select();
		$this->assign('list',$list);
        $this->assign('balance',$Tenant->balance/100);
		return $this->fetch();
	}

    public function indexApi() {
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $where = ['tenantId'=>session('TENANT_ID')];  //搜索条件
        if(session('member')['roleType'] == 2) {
            $where['id'] = session('member')['storeId'];
        }

        $list = $this->model->where($where)->limit($start,$length)->select();
        $count = $this->model->where($where)->count();
        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);
    }

	public function add() {
		$this->assign('week',$this->week);
		return $this->fetch();
	}

    //检测登录商户的门店数量，若大于等于1个，则提示，需要扣费
    private function checkOne() {
        $count = $this->model->where('tenantId',session('TENANT_ID'))->count();
        if($count > 0 ) {
            $fee = config('store_fee')/100;
            return [
                'status' => 2,
                'message' => '你已经开过店，再开店需要扣除'.$fee.'元服务费'
                ];
        } else {
            return [
                'status' => 1,
                'message' => '第一个门店'
            ];
        }
    }

    public function wxStatus() {  //判断是否微信授权
        $tenantId = session('TENANT_ID');
        $Tenant = \app\common\model\Tenant::get($tenantId);
        if($Tenant->wxStatus == 0 || !$Tenant->appId){
            return false;
        }
        return true;
    }

    //扣除开通多门店的费用
    private function deductions(){
        $status = true;
        $row = \app\admin\model\Tenant::field('balance')->where('id',session('TENANT_ID'))->find();  //查询余额
        if($row['balance'] < config('store_fee')) {
            $status = false;
        } else {
            \app\admin\model\tenant::where('id',session('TENANT_ID'))->setDec('balance',config('store_fee')); // 扣余额
            //插入消费记录

            $Recordconsumption = new Recordconsumption();
            $Recordconsumption->id = BaseHelper::getUUID();
            $Recordconsumption->tenantId = session('TENANT_ID');
            $Recordconsumption->record_type = 1;
            $Recordconsumption->money = config('store_fee');
            $Recordconsumption->save();
        }
        return $status;
    }

	public function addPost() {

        if(!$this->wxStatus()) {
            return show(0,'请先去授权小程序','请先去授权小程序');
        }
        // $tenantId = session('TENANT_ID');
        // $Tenant = \app\common\model\Tenant::get($tenantId);
        // if($Tenant->wxStatus == 0 || !$Tenant->appId){
        //     return show(0,'请先去授权小程序','请先去授权小程序');
        // }
	    Db::startTrans();
	    try{

            //扣除开店费 (第一个店铺可以免费开通)
            if($this->checkOne()['status'] == 2){
                if(!$this->deductions()){
                    return show(DictConstant::Merchant_balance_not,'余额不足请充值','余额不足请充值');
                }
            }

            $member = session('member');
            $post = input('post.');
            $data = $post['store'];

            //把其它经纬度转换成腾讯地图经纬度
            if($data['addressGeo']){
                $data['addressGeo'] = BaseHelper::CoordinateConvert($data['addressGeo']);
            }
            // return $post;

            if(!isset($data['openWeek'])) {
                $data['openWeek'] = '';
            }

            $id = get_uniqid_id();   //门店主键id
            //创建门店二维码
            $storecode = MiniProgramHelp::getStoreCode(session('TENANT_ID'),$id);
            if(!$storecode){
                return show(DictConstant::StoreQrCodeError,'生成店铺二维码失败','生成店铺二维码失败');
            }
            $data['id'] = $id;
            $data['tenantId'] = session('TENANT_ID');
            $data['code'] = $member['tenantCode'];
            $data['createDate'] = date('Y-m-d H:i:s',time());
            $data['updateDate'] = date('Y-m-d H:i:s',time());
            $data['createOper'] = $member['id'];
            $data['updateOper'] = $member['id'];
            $data['qrCode'] = $storecode;

            $img = json_decode($data['storeImg'],true);
            foreach ($img as $i) {
                $storeimg[] = [
                    'id' => get_uniqid_id(),
                    'storeId' => $id,
                    'imgUrl' => strpos($i['imageUrl'],'imageView2') > 0 ? $i['imageUrl'] : $i['imageUrl'].'?imageView2/1/w/750/h/560',
                    'imgId' => $i['imageId'],
                    'tenantId' => session('TENANT_ID'),
                    'createDate' => date('Y-m-d H:i:s',time())
                ];
            }

            Db::table('storeimg')->insertAll($storeimg);
            unset($data['storeImg']);
            $add = $this->model->insert($data);
            if($add) {
                //创建达达门店  门店id
                $data['id'] = $id;
                $param = $this->dadaStore($data);
                $this->addDada($param);

            }

            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'开店成功','开店成功');
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),'开店失败','开店失败');
        }

	}

	private function dadaStore($data){
        //获取商户类目
        $tenantModel = new \app\admin\model\Tenant();
        $tenant = $tenantModel->getTenant(session('TENANT_ID'));
        //根据类目设定达达门店所属业务类型
        $category = $tenant->category;
        $business = $this->getDadaCategory($category);
        $data['business'] = $business?$business:19;
        $getParam = $this->getParam($data);
        //达达配置参数获取
      //  $getParam = $this->getParam($data);
        //将门店添加到达达配送
        return $getParam;
    }

    private function getDadaCategory($category){
        switch ($category){
            case "餐饮美食":
                return 1;  //对应达达业务类型食品小吃
            case "盆栽":
                return 2;   //对应达达业务类型鲜花
            case "娱乐票务":
                return 8;   //对应达达业务类型文印票务
            case "儿童玩具":
                return 25;//对应达达业务类型小商品市场
            case "休闲娱乐":
                return 19;
            case "箱包":
                return 19;//同城电商
            case "钟表":
                return 19;
            case "美妆":
                return 19;
            case "服饰":
                return 26;//对应达达业务类型服装
            case "数码家电":
                return 28;//对应达达业务类型数码
            case "景区景点":
                return 5;//对应达达业务类型其他
            case "旅馆酒店":
                return 5;
            case "租车":
                return 5;
            case "旅行社":
                return 5;
            case "婚庆":
                return 5;
        }
    }

    /**
     * @param $data
     * @return mixed
     * 创建店铺
     */
	private function addDada($data){
	   $merchantApi = new MerchantApi();
	   $result = $merchantApi->add($data);
	   return $result;
    }

    /**
     *获取达达对应参数
     */
    private function getParam($data){
        $param['station_name'] = $data["name"];
        $param['origin_shop_id'] = $data['id'];//门店编码
        $param['area_name'] = $data["district"];//区域名称
        $param['station_address'] = $data["detailed_address"];
        $param['contact_name'] = $data["contact_name"];     //联系人姓名
        //城市字符串截取
        $DadaTools = new DadaAddOrder();
        $city = $DadaTools->citySubstr(['cityName'=> $data['city']]);
        $param['city_name'] = $city;//城市名称
        $param['business'] = $data["business"];

//        //百度地图经纬度转换为高德地图经纬度
//        $gaodeAddressGeoArr = $this->baiduTransformationGaode($data['addressGeo']);
        $AddressGeoArr = explode(',',$data['addressGeo']);
        //当前门店经纬度分割
//        $addressGeoArr = $this->getLngAndLat($gaodeAddressGeoArr);
        $param['lng'] =  $AddressGeoArr[1];//经度
        $param['phone'] = $data["phone"];
        $param['lat'] =  $AddressGeoArr[0];//纬度
       // $param['station_name'] = $data["name"];
        return [$param];
    }

    /**
     * @param $gaodeAddressGeo
     * @return bool
     *百度经纬度转换为高德经纬度
     */
    private function baiduTransformationGaode($gaodeAddressGeo){
        $gaodeApi = new gaoDeApi();
        $gaodeAddressGeo = $gaodeApi->baiduTransformationGaode($gaodeAddressGeo,$gaodeApi::BAIDU);
        return $gaodeAddressGeo;
    }
    //当前门店经纬度分割
    private function getLngAndLat($addressGeo){
        $addressGeoArr = explode(',',$addressGeo);
        return $addressGeoArr;
    }

	public function edit() {
		$id = $this->request->param('id');
		$row = $this->model->where(['id'=>$id])->find();
		$img = Db::table('storeimg')->where(['storeId'=>$id,'tenantId'=>session('TENANT_ID')])->select();
        $imgId = [];
        foreach ($img as $v) {
            $imgId[] = $v['imgId'];
        }
		if($row['tenantId'] != session('TENANT_ID')) {  //验证所修改的是否为同一店铺的门店
			return $this->error('参数有误');
		}
		$this->assign('week',$this->week);
		$this->assign('row',$row);
        $this->assign('img',$img);
		$this->assign('imgId',implode(',', $imgId));
		return $this->fetch();
	}
    
	public function editPost() {
		$post = input('post.');
        // return $post;

        $data = $post['store'];
        //把其它经纬度转换成腾讯地图经纬度
        if($data['addressGeo']){
            $data['addressGeo'] = BaseHelper::CoordinateConvert($data['addressGeo']);
        }
		$id = $data['id'];   //门店ID
		unset($data['id']);
		$data['openWeek'] = $data['openWeek'];
		$data['updateDate'] = date('Y-m-d H:i:s',time());
		$data['updateOper'] = session('member')['id'];

        //图片处理，先删除之前所有关联图片，再插入
        Db::table('storeimg')->where('storeId',$id)->delete();
        $img = json_decode($data['storeImg'],true);
        foreach ($img as $i) {
            $storeimg[] = [
                'id' => get_uniqid_id(),
                'storeId' => $id,
                'imgUrl' => strpos($i['imageUrl'],'imageView2') > 0 ? $i['imageUrl'] : $i['imageUrl'].'?imageView2/1/w/750/h/560',
                'imgId' => $i['imageId'],
                'tenantId' => session('TENANT_ID'),
                'createDate' => date('Y-m-d H:i:s',time())
            ];
        }
        Db::table('storeimg')->insertAll($storeimg);
        unset($data['storeImg']);

        $save = $this->model->where(['id'=>$id])->update($data);
        if($save) {
            $data['id'] = $id;

            $res = $this->editDada($data);
            return json(['status'=>'1','message'=>'修改成功']);
        } else {
            return json(['status'=>'2','message'=>'网络出错，请重试']);
        }
	}

    /**
     *
     */
	public function editDada($data){
        $param = $this->dadaStore($data);


	    $merchantApi = new MerchantApi();
        $merchantApi->edit($param[0]);
    }

	/**
	 * 门店-查看已选货架商品
	 * @return
	 */
	public function product() {
		$id = $this->request->param('storeId');  //门店id
		$store = $this->model->where(['tenantId'=>session('TENANT_ID')])->select();
        $type = Producttype::where(['tenantId'=>session('TENANT_ID')])->select();
		// dump($products);

        $this->assign('store',$store);
        $this->assign('type',$type);
        $this->assign('storeId',$id);
		return $this->fetch();
	}

    //获取本门店所选商品
    public function productApi(){
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $storeId = $param['storeId'];  //门店ID
        $order = 'created DESC';

        $where = ['store_id'=>$storeId];
        if($param['search']['value']){
            $search = json_decode($param['search']['value'],true);
            if($search['order'] == 'sell') {  //TODO 按热卖数量排序
                $order = 'created';
            } else if($search['order'] == 'create_time'){  //按时间降序
                $order = 'created DESC';
            }else{  //首页推荐的在先
                $order = $search['order'];
            }

            if(!empty($search['typeId'])){ //按类型搜索
                $where['typeId'] = ['=', $search['typeId']];
            }
        }

        $list = Storeproduct::field('a.*,b.id pid,b.title,b.imgUrl,b.typeId,b.updateDate,b.currentPrice')->alias('a')->join('product b','a.product_id=b.id')->where($where)->limit($start,$length)->order($order)->select();
        $count = Storeproduct::field('a.*,b.id pid,b.title,b.imgUrl,b.typeId,b.updateDate,b.currentPrice')->alias('a')->join('product b','a.product_id=b.id')->where($where)->count();

        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);

    }

    /**一次性获取该门店已经选取的商品
     * @return \think\response\Json
     */
    public function getselectproduct(){
        (new IDMustBePostiveInt())->goCheck();
        $param = Request::instance()->param();

        $where = [
            'store_id' => $param['id']
        ];
        $Storeproduct = Storeproduct::where($where)->select();
        if($Storeproduct){
            return show('1','ok',$Storeproduct);
        }
    }

    //取得所有商品数据，客户端分页
    public function productList() {
        $request = Request::instance();
        $param = $request->param();


        $where['tenantId'] = session('TENANT_ID');

        $plist = Product::where($where)->where('isVirtual','neq',1)->order('createDate DESC')->select();
        $count = Product::where($where)->where('isVirtual','neq',1)->count();
        $res = [
            'status' => '1',
            // 'draw' => $param['draw'],
            'data' => $plist,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];
        return json($res);
    }

    /**
     * 删除门店商品
     * 检查是否有未完成订单，既待付款
     * 删除前检查是否添加到拼团或积分商品，若是，则不允许删除
     */
    public function productDel(){
        $request = Request::instance();
        $id = $request->param('id');  //主键ID
        $storeId = $request->param('storeId');  //门店ID
        $product_id = $request->param('product_id');  //商品ID
        $code = '1';
        $message = '删除成功';
        $check = $this->check($storeId,$product_id,$code,$message);
        if(!$check) {
            return json(['code'=>$code,'message'=>$message]);
        }
        Db::startTrans();
        try{
            $del = Storeproduct::where(['id'=>$id])->delete();
            if($del) {
                //如果用户购物车添加了此商品，也要删除购物车里的商品
                $shop = Shoppingcar::where(['storeId'=>$storeId,'productId'=>$product_id,'status'=>1])->find();
                if($shop){
                    $shop->delete();
                }
                Db::commit();
                return json(['code'=>'1','message'=>'删除成功']);
            }
        }catch (Exception $ex){
            Db::rollback();
            return json(['code'=>'2','message'=>'删除失败，请重试']);
        }
    }

    //根据商品id与门店id检测是否有未完成订单
    public function checkOrder(){
        $request = Request::instance();
        $storeId = $request->param('storeId');  //门店ID
        $product_id = $request->param('product_id');  //商品ID
        $code = '1';
        $message = '可删除';
        $this->check($storeId,$product_id,$code,$message);
        return json(['code'=>$code,'message'=>$message]);

    }

    private function check($storeId,$product_id,&$code,&$message){
        $group = Groupproduct::where(['storeId'=>$storeId,'productId'=>$product_id,'status'=>1])->find();
        if($group) {
            $code = '2';
            $message = '此商品被选为拼团商品，不能删除';
            return false;
        }
        $interal = Integralproducts::where(['storeId'=>$storeId,'productId'=>$product_id,'status'=>1])->find();
        if($interal) {
            $code = '2';
            $message = '此商品被选为积分商品，不能删除';
            return false;
        }
        $wxcomponent = Wxcomponentconf::alias('a')->join('wxframeconf b','a.frameId=b.id')->where(['linkType'=>'1','linkId'=>$product_id,'b.storeId'=>$storeId])->find();
        if($wxcomponent) {
            $code = '2';
            $message = '此商品被选为首页展示链接，不可删除';
            return false;
        }

//        $shop = Shoppingcar::where(['storeId'=>$storeId,'productId'=>$product_id,'status'=>1])->find();
//        if($shop) {
//            $code = '2';
//            $message = '此商品被用户加入购物车，不可删除';
//            return false;
//        }

        $find = Order::alias('a')->join('orderproductdetail b','a.id=b.orderId')->where(['b.productId'=>$product_id,'a.storeId'=>$storeId,'a.linkType'=>0])->where('a.status','not in',[4,5,7])->find();
        if($find) {
            $code = '2';
            $message = '此商品有未完成订单，不能删除';
            return false;
        }
        return true;
    }

    /**
     * 门店商品-设为推荐
     */
    public function recommend() {
        $request = Request::instance();
        $param = $request->param();
        $upd = Storeproduct::where('id',$param['id'])->update($param);
        if($upd)
            return json(['code'=>'1','message'=>'推荐成功']);
        return json(['code'=>'2','message'=>'出错，请重试']);
    }

	// 门店-选择货架-保存
	public function selectPost() {
		$request = Request::instance();
        $param = $request->param();
        // return $param;
        $product = json_decode($param['selectId'],true);
        $product = (Array)$product['selectId'];

		$storeproductMdl = new Storeproduct();

		$select = $storeproductMdl->field('product_id')->where('store_id',$param['store_id'])->select();
		$sid = [];
		foreach ($select as $v) {   //获得已选商品id
			$sid[] = $v['product_id'];
		}
		$add = array_diff($product, $sid);   //获得需要添加的商品id
		$del = array_diff($sid, $product);   //获得需要删除的商品id
		// dump($add);
		// dump($del);die;
		$data = [];
		foreach ($add as $v) {
			$data[] = [
                'id' => get_uniqid_id(), 
				'store_id' => $param['store_id'],
				'product_id' => $v,
				'created' => time()
			];
		}
		$storeproductMdl->insertAll($data);
		foreach ($del as $d) {
			$storeproductMdl->where(['store_id'=>$param['store_id'],'product_id'=>$d])->delete();
		}
        return json(['status'=>'1','message'=>'修改成功']);
		
	}

	//门店下货架商品的排序
	public function sort() {
		$post  = input('post.');
		foreach ($post['id'] as $k => $v) {
			$tmp = ['id'=>$v,'orderNo'=>$post['sort'][$k]];
			Db::table('storeproduct')->update($tmp);
		}
		return $this->success('修改成功','/index.php/admin/store/product/id/'.$post['store_id']);
	}


	public function delete() {
		//删除门店，当门店下有店员信息或货架信息时，不允许删除
        $request = Request::instance();
        $id = $request->param('id');

		$operator = Db::table('operator')->where('storeId',$id)->find();
		if($operator) {  //门店下有店员信息，不能删除
            return json(['status'=>'2','message'=>'门店下有店员信息，不能删除']);
		}

		$product = Db::table('storeproduct')->where('store_id',$id)->find();
		if($product) {  //门店下有商品，不能删除
            return json(['status'=>'2','message'=>'门店下有商品信息，不能删除']);
		}

        $where = ['id'=>$id,'tenantId'=>session('TENANT_ID')];

        //删除门店图片
        Db::table('storeimg')->where('storeId',$id)->delete();

        if($this->model->where($where)->delete()) {
            return json(['status'=>'1','message'=>'删除成功']);
        } else {
            return json(['status'=>'2','message'=>'网络出错，请重试']);
        }
	}

    /**
     * 获取门店信息
     *
     * @return \think\response\Json
     */
    public function getStoreInfo() {
        if($this->request->isAjax()){
            $id = $this->request->param('storeId');
            $info = $this->model->where(['id' => $id])->find();
            $img = Db::table('storeimg')->where(['storeId' => $id,'tenantId'=>session('TENANT_ID')])->find();
            $info->storeImg = $img['imgUrl'];

            return json(['status'=>'1', 'data'=>$info]);
        }
    }

    //店铺打烊

    public function isclose(Request $request){
        $Tenant = \app\common\model\Tenant::get(session('TENANT_ID'));
        $param = $request->param();
        if(!$this->checkiscloseparam($param)){
            return show(config('status.ERROR_STATUS'),'请求参数不合法','请求参数不合法');
        }
        if($request->isPost()){
            $Store = \app\admin\model\Store::get($param['id']);
            if(!$Store || $Store->tenantId != $Tenant->id){
                return show(config('status.ERROR_STATUS'),'该店铺不合法','该店铺不合法');
            }
            if($param['is_close'] ==1){
                //打烊
                $Store->is_close = 2;
                $Store->save();
            }else{
                //开启营业
                $Store->is_close = 1;
                $Store->save();
            }
            return show(config('status.SUCCESS_STATUS'),'设置成功','设置成功');
        }
    }

    private function checkiscloseparam($param){
        if(empty($param['id'])){
            return false;
        }
        if($param['is_close']!=1 && $param['is_close']!=2){
            return false;
        }

        return true;
    }
}